package com.xmy.cultivate.controller;

import com.aliyun.facebody20191230.models.SearchFaceResponse;
import com.aliyun.facebody20191230.models.SearchFaceResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.request.BookGrantInfoRs;
import com.xmy.cultivate.entity.request.BookGrantRs;
import com.xmy.cultivate.entity.request.FaceDetectLivingRequest;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.GradeMapper;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.Result;
import com.xmy.cultivate.util.ResultCode;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/bookGrantInfo")
@Scope("prototype")
public class BookGrantInfoController extends BaseController {

    @Value("${aliyun.AccessKeyID}")
    String accessKeyId;

    @Value("${aliyun.AccessKeySecret}")
    String accessKeySecret;

    @Value("${aliyun.oss.endpoint}")
    String ossEndpoint;

    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;

    @Autowired
    IOssUploadService iOssUploadService;


    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IFaceDbService iFaceDbService;

    @Autowired
    IAliyunFaceService iAliyunFaceService;

    @Autowired
    IStudentFaceManyDetailService iStudentFaceManyDetailService;

    @Autowired
    ILogRecordService iLogRecordService;

    @Autowired
    IBookGrantInfoService iBookGrantInfoService;

    @Autowired
    IBookStudentService iBookStudentService;

    @Autowired
    IStudentService iStudentService;
    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    IBookTextService iBookTextService;

    /**
     * @param upload
     * @param request
     * @param schoolId
     * @param subjectsId
     * @param adminIdParam
     * @return
     */
    @RequiresPermissions(value = "FaceBook")
    @PostMapping("/studentGrantForFace")
    public Result studentGrantForFace(@RequestParam("file") MultipartFile upload, HttpServletRequest request,
                                      @RequestParam(value = "schoolId", required = false) Long schoolId,
                                      @RequestParam(value = "subjectsId", required = false) Long subjectsId,
                                      @RequestParam(value = "adminId", required = false) Long adminIdParam) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
        Integer faceType = 1;
        if (adminIdParam != null) {
            this.adminId = adminIdParam;
        }

        if (quarterNow == null) {
            throw new CommonException(ResultCode.quarterNo);
        }

        Integer lessonType = 1;
        Staff staff = iStaffService.getOneById(this.adminId);
        if (subjectsId == null) {
            //return new Result(Code.ERROR, "", "请先选择签到的科目");
        }

        //是否需要人脸数据校验
        Company company = iCompanyService.getById(1L);
        boolean IsFaceDataVerify = false;
        if (company != null) {
            if (company.getIsFaceDataVerify().equals(1) || company.getIsFaceDataVerify().equals(2)) {
                IsFaceDataVerify = true;
            }
        }

        Map<String, Object> mapResult = new HashMap<>();
        String ossImageUrl = "";

        //随机获取出一个校区
        Organization schoolRand = iOrganizationService.getOneRand();
        Long schoolIdForFace = schoolRand.getId();

        try {
            if (upload == null || upload.isEmpty()) {
                return new Result(Code.ERROR, "", "没有上传文件，请关闭重新打开");
            }
            LocalDate localDate = LocalDate.now();
            LocalDateTime localDateTime = LocalDateTime.now().withNano(0);

            FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

            //上传文件的位置,默认会在项目根目录找static文件夹,需手动创建,不然找到是临时路径。
            //String path = request.getSession().getServletContext().getRealPath("/uploads/header");
            //System.out.println("path:"+path);
            //判断该路径是否存在

            String directoryName = "face-sign" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();//签到图片目录
            String uploadUrl = uploadFileLocation + "/" + directoryName;
            File file = new File(uploadUrl);
            // 若不存在则创建该文件夹
            if (!file.exists()) {
                file.mkdirs();
            }
            //获取上传文件的后缀名
            String fileType = upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
            // 获取上传文件的名称
            //String filename = upload.getOriginalFilename();
            // 把文件的名称设置唯一值，uuid
            //拼接图片
            String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
            String uuid = date + System.currentTimeMillis();
            String filename = uuid + fileType;
            // todo 把文件名存入数据库(此步骤省略)
            mapResult.put("signDateTime", localDateTime.toString().replace("T", " "));
            // 完成文件上传

            upload.transferTo(new File(uploadUrl, filename));
            String filePath = uploadUrl + "/" + filename;
            String saveName = filename;

            boolean ossUpRs = iOssUploadService.upFile(filePath, saveName, directoryName);//上传到oss

            if (ossUpRs) {
                ossImageUrl = this.showImgEndpoint + "/" + directoryName + "/" + saveName;

                //System.out.println("ossImageUrl:"+ossImageUrl);
                SearchFaceResponse searchFaceResponse = iAliyunFaceService.searchFace(faceDb.getDbName(), schoolIdForFace, ossImageUrl);
                if (searchFaceResponse.getBody().getData() == null) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10008");
                    return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到人脸数据，请重新采集");
                }

                List<SearchFaceResponseBody.SearchFaceResponseBodyDataMatchList> searchFaceResponseBodyDataMatchList = searchFaceResponse.getBody().getData().getMatchList();
                if (searchFaceResponseBodyDataMatchList.size() > 0) {
                    SearchFaceResponseBody.SearchFaceResponseBodyDataMatchList faceResponseBodyDataMatchList = searchFaceResponseBodyDataMatchList.get(0);
                    Float QualitieScore = faceResponseBodyDataMatchList.getQualitieScore();
                    Float confidence = Float.parseFloat("75.62");//转换后的置信度
                    Float score = Float.parseFloat("0.6");//人脸的相似度

                    Float maxConfidence = Float.parseFloat("0");
                    Float maxScore = Float.parseFloat("0");

                    SearchFaceResponseBody.SearchFaceResponseBodyDataMatchListFaceItems findFaceResponseBodyDataMatchListFaceItem = null;
                    for (SearchFaceResponseBody.SearchFaceResponseBodyDataMatchListFaceItems searchFaceResponseBodyDataMatchFaceItems : faceResponseBodyDataMatchList.getFaceItems()) {
                        if (findFaceResponseBodyDataMatchListFaceItem == null) {
                            findFaceResponseBodyDataMatchListFaceItem = searchFaceResponseBodyDataMatchFaceItems;
                        } else {
                            //System.out.println("searchFaceResponseBodyDataMatchFaceItems.getConfidence:"+searchFaceResponseBodyDataMatchFaceItems.getConfidence());
                            if (findFaceResponseBodyDataMatchListFaceItem != null && searchFaceResponseBodyDataMatchFaceItems.getConfidence() > findFaceResponseBodyDataMatchListFaceItem.getConfidence()) {
                                findFaceResponseBodyDataMatchListFaceItem = searchFaceResponseBodyDataMatchFaceItems;
                            }
                        }
                    }
                    if (findFaceResponseBodyDataMatchListFaceItem != null) {
                        maxConfidence = findFaceResponseBodyDataMatchListFaceItem.getConfidence();
                        maxScore = findFaceResponseBodyDataMatchListFaceItem.getScore();
                    }

                    if (findFaceResponseBodyDataMatchListFaceItem != null && findFaceResponseBodyDataMatchListFaceItem.getConfidence() >= confidence && findFaceResponseBodyDataMatchListFaceItem.getScore() > score) {
                        String entityId = findFaceResponseBodyDataMatchListFaceItem.getEntityId();
                        findFaceResponseBodyDataMatchListFaceItem.getFaceId();
                        findFaceResponseBodyDataMatchListFaceItem.getScore();
                        findFaceResponseBodyDataMatchListFaceItem.getExtraData();

                        QueryWrapper<StudentFaceManyDetail> studentFaceManyQueryWrapper = new QueryWrapper<>();
                        studentFaceManyQueryWrapper.eq("entity_id", entityId);
                        studentFaceManyQueryWrapper.eq("ali_account", schoolRand.getAliAccount());
                        studentFaceManyQueryWrapper.groupBy("ali_account", "student_id");
                        studentFaceManyQueryWrapper.orderByDesc("created_at");
                        //studentFaceDataQueryWrapper.eq("school_id",schoolId);
                        List<StudentFaceManyDetail> studentFaceDataList = iStudentFaceManyDetailService.list(studentFaceManyQueryWrapper);

                        Student student = null;
                        //找到的学生
                        List<Student> studentList = new ArrayList<>();
                        for (StudentFaceManyDetail studentFaceMany : studentFaceDataList) {
                            student = iStudentService.getById(studentFaceMany.getStudentId());
                            if (student == null) {
                                continue;
                            }
                            studentList.add(student);
                        }
                        if (!Objects.isNull(student)) {

                            BookStudent bookStudent = new BookStudent();
                            bookStudent.setYearPart(quarterNow.getYearPart());
                            bookStudent.setQuarterNum(quarterNow.getNum());
                            bookStudent.setStudentId(student.getId());
                            bookStudent.setSchoolId(schoolId);
                            bookStudent.setStudentName(student.getName());
                            bookStudent.setSubjectsId(subjectsId);
                            bookStudent.setLessonType(1);

                            Result rsGrant = iBookStudentService.grantBookForStudent(bookStudent, ossImageUrl);

                            return rsGrant;
                        } else {
                            mapResult.put("imageUrl", ossImageUrl);
                            mapResult.put("signCode", "10008");
                            return new Result(Code.FACE_ERROR, mapResult, "学生信息不存在");
                        }
                    } else {
                        mapResult.put("imageUrl", ossImageUrl);
                        mapResult.put("signCode", "10008");
                        return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到学生人脸数据,匹配到的分值为：" + maxConfidence);
                    }

                } else {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10024");
                    return new Result(Code.FACE_ERROR, mapResult, "签到失败,没有找到人脸数据");
                }
            } else {
                mapResult.put("imageUrl", "");
                mapResult.put("signCode", "10009");
                return new Result(Code.FACE_ERROR, mapResult, "签到失败，请重新签到");//(图片上传不成功)
            }
        } catch (Exception e) {
            e.printStackTrace();
            mapResult.put("signCode", "50000");
            mapResult.put("imageUrl", ossImageUrl);
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("人脸签到失败" + e.getMessage());
            logRecord.setLevel(5);

            String msg = e.getMessage();
            //boolean rs = a.contains("image not found face1");//image quality score not matched
            String typMsg = "";
            if (msg.contains("image not found face")) {
                typMsg = ":图片中没有人脸";
            } else if (msg.contains("image quality score not matched")) {
                typMsg = ":图片比较模糊";
            } else if (msg.contains("请检查帐号是否欠费")) {
                if (schoolRand != null) {
                    typMsg = schoolRand.getAliAccount() + "帐号欠费，请联系智能部充值再签到";
                    logRecord.setRemark(schoolRand.getAliAccount() + "帐号欠费，请联系智能部充值再签到");
                    logRecord.setLevel(6);
                } else {
                    typMsg = e.getMessage();
                }
            } else {
                typMsg = e.getMessage();
            }
            iLogRecordService.save(logRecord);

            return new Result(Code.FACE_ERROR, mapResult, "签到失败" + typMsg);
        }
    }


    @PostMapping("/studentGrant")
    public Result studentGrant(@RequestParam(value = "studentId", required = false) Long studentId) {
        return null;
    }


    /**
     * 教师发放
     *
     * @return
     */
    @RequiresPermissions(value = "FaceBook")
    @PostMapping("/teacherGrant")
    public Result teacherGrant(@RequestParam("file") MultipartFile upload, HttpServletRequest request,
                               @RequestParam(value = "yearPart", required = false) Integer yearPart,
                               @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                               @RequestParam(value = "schoolId", required = false) Long schoolId,
                               @RequestParam(value = "subjectsId", required = false) Long subjectsId,
                               @RequestParam(value = "adminId", required = false) Long adminIdParam,
                               @RequestParam(value = "textbookType", required = false) Integer textbookType // 1教材，2为纸张
    ) {

        Integer faceType = 2;

        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        if (adminIdParam != null) {
            this.adminId = adminIdParam;
        }

        if (quarterNow == null) {
            throw new CommonException(ResultCode.quarterNo);
        }

        Integer lessonType = 1;
        Staff staff = iStaffService.getOneById(this.adminId);
        if (subjectsId == null) {
            //return new Result(Code.ERROR, "", "请先选择发放的科目");
        }

        //是否需要人脸数据校验
        Company company = iCompanyService.getById(1L);
        boolean IsFaceDataVerify = false;
        if (company != null) {
            if (company.getIsFaceDataVerify().equals(1) || company.getIsFaceDataVerify().equals(2)) {
                IsFaceDataVerify = true;
            }
        }

        Map<String, Object> mapResult = new HashMap<>();
        String ossImageUrl = "";

        //随机获取出一个校区
        Organization schoolRand = iOrganizationService.getOneRand();
        Long schoolIdForFace = schoolRand.getId();

        try {
            if (upload == null || upload.isEmpty()) {
                return new Result(Code.ERROR, "", "没有上传文件，请关闭重新打开");
            }
            LocalDate localDate = LocalDate.now();
            LocalDateTime localDateTime = LocalDateTime.now().withNano(0);

            FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

            //上传文件的位置,默认会在项目根目录找static文件夹,需手动创建,不然找到是临时路径。
            //String path = request.getSession().getServletContext().getRealPath("/uploads/header");
            //System.out.println("path:"+path);
            //判断该路径是否存在

            String directoryName = "face-sign" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();//签到图片目录
            String uploadUrl = uploadFileLocation + "/" + directoryName;
            File file = new File(uploadUrl);
            // 若不存在则创建该文件夹
            if (!file.exists()) {
                file.mkdirs();
            }
            //获取上传文件的后缀名
            String fileType = upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
            // 获取上传文件的名称
            //String filename = upload.getOriginalFilename();
            // 把文件的名称设置唯一值，uuid
            //拼接图片
            String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
            String uuid = date + System.currentTimeMillis();
            String filename = uuid + fileType;
            // todo 把文件名存入数据库(此步骤省略)
            mapResult.put("signDateTime", localDateTime.toString().replace("T", " "));
            // 完成文件上传

            upload.transferTo(new File(uploadUrl, filename));
            String filePath = uploadUrl + "/" + filename;
            String saveName = filename;

            boolean ossUpRs = iOssUploadService.upFile(filePath, saveName, directoryName);//上传到oss

            if (ossUpRs) {
                ossImageUrl = this.showImgEndpoint + "/" + directoryName + "/" + saveName;

                //System.out.println("ossImageUrl:"+ossImageUrl);
                SearchFaceResponse searchFaceResponse = iAliyunFaceService.searchFace(faceDb.getDbName(), schoolIdForFace, ossImageUrl);
                if (searchFaceResponse.getBody().getData() == null) {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10008");
                    return new Result(Code.FACE_ERROR, mapResult, "发放失败,没有找到人脸数据，请重新采集");
                }

                List<SearchFaceResponseBody.SearchFaceResponseBodyDataMatchList> searchFaceResponseBodyDataMatchList = searchFaceResponse.getBody().getData().getMatchList();
                if (searchFaceResponseBodyDataMatchList.size() > 0) {
                    SearchFaceResponseBody.SearchFaceResponseBodyDataMatchList faceResponseBodyDataMatchList = searchFaceResponseBodyDataMatchList.get(0);
                    Float QualitieScore = faceResponseBodyDataMatchList.getQualitieScore();
                    Float confidence = Float.parseFloat("75.62");//转换后的置信度
                    Float score = Float.parseFloat("0.6");//人脸的相似度

                    Float maxConfidence = Float.parseFloat("0");
                    Float maxScore = Float.parseFloat("0");

                    SearchFaceResponseBody.SearchFaceResponseBodyDataMatchListFaceItems findFaceResponseBodyDataMatchListFaceItem = null;
                    for (SearchFaceResponseBody.SearchFaceResponseBodyDataMatchListFaceItems searchFaceResponseBodyDataMatchFaceItems : faceResponseBodyDataMatchList.getFaceItems()) {
                        if (findFaceResponseBodyDataMatchListFaceItem == null) {
                            findFaceResponseBodyDataMatchListFaceItem = searchFaceResponseBodyDataMatchFaceItems;
                        } else {
                            //System.out.println("searchFaceResponseBodyDataMatchFaceItems.getConfidence:"+searchFaceResponseBodyDataMatchFaceItems.getConfidence());
                            if (findFaceResponseBodyDataMatchListFaceItem != null && searchFaceResponseBodyDataMatchFaceItems.getConfidence() > findFaceResponseBodyDataMatchListFaceItem.getConfidence()) {
                                findFaceResponseBodyDataMatchListFaceItem = searchFaceResponseBodyDataMatchFaceItems;
                            }
                        }
                    }
                    if (findFaceResponseBodyDataMatchListFaceItem != null) {
                        maxConfidence = findFaceResponseBodyDataMatchListFaceItem.getConfidence();
                        maxScore = findFaceResponseBodyDataMatchListFaceItem.getScore();
                    }

                    if (findFaceResponseBodyDataMatchListFaceItem != null && findFaceResponseBodyDataMatchListFaceItem.getConfidence() >= confidence && findFaceResponseBodyDataMatchListFaceItem.getScore() > score) {
                        String entityId = findFaceResponseBodyDataMatchListFaceItem.getEntityId();
                        findFaceResponseBodyDataMatchListFaceItem.getFaceId();
                        findFaceResponseBodyDataMatchListFaceItem.getScore();
                        findFaceResponseBodyDataMatchListFaceItem.getExtraData();

                        Staff teacherInfo = iStaffService.getById(entityId);

                        //iBookGrantInfoService.getGrantLog();

                        Integer grantType = 4;//发放类型，4教师，5学生
                        Integer status = 3;//未发放
                        if (textbookType == 1) {
                            // 发放教材
                            //List<BookGrantInfo> bookGrantInfoList = new ArrayList<>();
                            //Long needCount = iBookStudentService.getNeedGrantCount(yearPart, quarterNum, schoolId, subjectsId, teacherInfo.getId(), status);
                            mapResult.put("imageUrl", ossImageUrl);
                            mapResult.put("teacherId", teacherInfo.getId());
                            mapResult.put("teacherName", teacherInfo.getName());
                            mapResult.put("signCode", "10001");
                            /*if (needCount > 0) {
                                boolean grantRs = iBookStudentService.bookGrant(yearPart, quarterNum, schoolId, subjectsId, teacherInfo.getId(), grantType, ossImageUrl, this.adminId);
                                if (grantRs) {
                                    bookGrantInfoList = iBookGrantInfoService.getGrantLog(yearPart, quarterNum, schoolId, subjectsId, teacherInfo.getId(), grantType, 1);
                                    mapResult.put("signCode", "10001");
                                } else {
                                    mapResult.put("signCode", "50000");
                                    return new Result(Code.FACE_ERROR, mapResult, "发放失败");
                                }

                            } else {
                                mapResult.put("signCode", "10002");
                                return new Result(Code.OK, mapResult, "没有可发放教材");
                            }*/
                            //mapResult.put("grantCount", needCount);
                            //mapResult.put("bookGrantInfoList", bookGrantInfoList);

                        } else if (textbookType == 2) {
                            // 发放纸张
                            List<BookGrantInfo> bookGrantInfoList = new ArrayList<>();
                            Long needCount = iBookStudentService.getNeedGrantPaperCount(yearPart, quarterNum, schoolId, subjectsId, teacherInfo.getId(), status);
                            mapResult.put("imageUrl", ossImageUrl);
                            mapResult.put("teacherId", teacherInfo.getId());
                            mapResult.put("teacherName", teacherInfo.getName());
                            if (needCount > 0) {
                                boolean grantRs = iBookStudentService.bookGrantPaper(yearPart, quarterNum, schoolId, subjectsId, teacherInfo.getId(), grantType, ossImageUrl, this.adminId);
                                if (grantRs) {
                                    bookGrantInfoList = iBookGrantInfoService.getGrantPaperLog(yearPart, quarterNum, schoolId, subjectsId, teacherInfo.getId(), grantType, 1);
                                    mapResult.put("signCode", "10001");
                                } else {
                                    mapResult.put("signCode", "50000");
                                    return new Result(Code.FACE_ERROR, mapResult, "发放失败");
                                }

                            } else {
                                mapResult.put("signCode", "10002");
                                return new Result(Code.OK, mapResult, "没有可发放教材");
                            }
                            mapResult.put("grantCount", needCount);
                            mapResult.put("bookGrantInfoList", bookGrantInfoList);
                        }

                        return new Result(Code.OK, mapResult, "");
                    } else {
                        mapResult.put("imageUrl", ossImageUrl);
                        mapResult.put("signCode", "10008");
                        return new Result(Code.FACE_ERROR, mapResult, "发放失败,没有找到教师人脸数据,匹配到的分值为：" + maxConfidence);
                    }

                } else {
                    mapResult.put("imageUrl", ossImageUrl);
                    mapResult.put("signCode", "10024");
                    return new Result(Code.FACE_ERROR, mapResult, "发放失败,没有找到人脸数据");
                }
            } else {
                mapResult.put("imageUrl", "");
                mapResult.put("signCode", "10009");
                return new Result(Code.FACE_ERROR, mapResult, "发放失败，请重新发放");//(图片上传不成功)
            }
        } catch (Exception e) {
            e.printStackTrace();
            mapResult.put("signCode", "50000");
            mapResult.put("imageUrl", ossImageUrl);
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("发放失败" + e.getMessage());
            logRecord.setLevel(5);

            String msg = e.getMessage();
            //boolean rs = a.contains("image not found face1");//image quality score not matched
            String typMsg = "";
            if (msg != null && msg.length() > 0) {
                if (msg.contains("image not found face")) {
                    typMsg = ":图片中没有人脸";
                } else if (msg.contains("image quality score not matched")) {
                    typMsg = ":图片比较模糊";
                } else if (msg.contains("请检查帐号是否欠费")) {
                    if (schoolRand != null) {
                        typMsg = schoolRand.getAliAccount() + "帐号欠费，请联系智能部充值再签到";
                        logRecord.setRemark(schoolRand.getAliAccount() + "帐号欠费，请联系智能部充值再签到");
                        logRecord.setLevel(6);
                    } else {
                        typMsg = e.getMessage();
                    }
                } else {
                    typMsg = e.getMessage();
                }
            }
            iLogRecordService.save(logRecord);

            return new Result(Code.FACE_ERROR, mapResult, "签到失败" + typMsg);
        }
    }

    @GetMapping("/getGrantLogDetail")
    public Result getGrantLogDetail(
            @RequestParam(value = "yearPart", required = false) Integer yearPart,
            @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "teacherId", required = false) Long teacherId,
            @RequestParam(value = "subjectsId", required = false) Long subjectsId,
            @RequestParam(value = "bookTextId", required = false) Long bookTextId,
            @RequestParam(value = "grantDateTime", required = false) String grantDateTime,
            @RequestParam(value = "grantType", required = false, defaultValue = "4") Integer grantType, //教师：4，学生5
            @RequestParam(value = "type", required = false, defaultValue = "1") Integer type,
            @RequestParam(value = "bookTextType", required = false) Integer bookTextType,
            @RequestParam(value = "classTypeId", required = false) Long classTypeId,
            @RequestParam(value = "yearClassId", required = false) String yearClassId,
            @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum,
            @RequestParam(value = "studentName", required = false) String studentName,
            @RequestParam(value = "gradeId", required = false) String gradeId,
            @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails// 0列表，1详情

    ) {
        List<BookGrantInfoRs> bookGrantInfoRsList;
        if (type.equals(1)) {
            bookGrantInfoRsList = iBookGrantInfoService.getGrantLogDetail(yearPart, quarterNum, schoolId, subjectsId, teacherId, grantType, bookTextId, grantDateTime, bookTextType, classTypeId, yearClassId, lessonNum, studentName,gradeId, isDetails);
        } else {
            bookGrantInfoRsList = iBookGrantInfoService.getGrantLogDetailPaper(yearPart, quarterNum, schoolId, subjectsId, teacherId, grantType, grantDateTime);
        }
        return new Result(Code.OK, bookGrantInfoRsList, "");
    }

    /**
     * 获取发放记录
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param grantId
     * @param subjectsId
     * @param grantType  发放类型，4教师，5学生
     * @return
     */
    @GetMapping("/getGrantLog")
    public Result getGrantLog(
            @RequestParam(value = "yearPart", required = false) Integer yearPart,
            @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "grantId", required = false) Long grantId,
            @RequestParam(value = "subjectsId", required = false) Long subjectsId,
            @RequestParam(value = "grantType", required = false, defaultValue = "4") Integer grantType,
            @RequestParam(value = "textbookType", required = false, defaultValue = "1") Integer textbookType // 1教材，2纸张
    ) {

        List<BookGrantInfo> bookGrantInfoList;
        if (textbookType.equals(1)) {
            bookGrantInfoList = iBookGrantInfoService.getGrantLog(yearPart, quarterNum, schoolId, subjectsId, grantId, grantType, null);
        } else {
            bookGrantInfoList = iBookGrantInfoService.getGrantPaperLog(yearPart, quarterNum, schoolId, subjectsId, grantId, grantType, null);
        }
        return new Result(Code.OK, bookGrantInfoList, "");
    }


    /**
     * 老师可发放
     *
     * @param yearPart
     * @param quarterNum
     * @param teacherId
     * @param type       1按教材，2按班级
     * @return
     */
    @GetMapping("/getDistributable")
    public Result getDistributable(
            @RequestParam(value = "yearPart", required = false) Integer yearPart,
            @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "teacherId", required = false) Long teacherId,
            @RequestParam(value = "subjectsId", required = false) Long subjectsId,
            @RequestParam(value = "classTypeId", required = false) Long classTypeId,
            @RequestParam(value = "yearClassId", required = false) String yearClassId,
            @RequestParam(value = "status", required = false, defaultValue = "3") Integer status,
            @RequestParam(value = "isDetails", required = false, defaultValue = "0") Integer isDetails,// 0列表，1详情
            @RequestParam(value = "type", required = false, defaultValue = "1") Integer type, // 1按教材，2按班级
            @RequestParam(value = "bookTextType", required = false) String bookTextType,  //1学生用书，2教师用书
            @RequestParam(value = "studentName", required = false) String studentName,
            @RequestParam(value = "gradeId", required = false) String gradeId,
            @RequestParam(value = "bookTextId", required = false) String bookTextId,
            @RequestParam(value = "lessonNum", required = false, defaultValue = "0") Integer lessonNum
    ) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }
        if (schoolId == null) {
            return new Result(Code.ERROR, "", "请选择发放校区");
        }

        if (teacherId == null) {
            return new Result(Code.ERROR, "", "没有发放老师，请重新扫脸");
        }

        Organization schoolInfo = iOrganizationService.getById(schoolId);
        Staff staff = iStaffService.getById(teacherId);

        subjectsId = gradeMapper.getSubjectsForTeacherId(yearPart, quarterNum, schoolId, teacherId);
        if (subjectsId == null) {
            return new Result(Code.ERROR, "", "【" + staff.getName() + "】老师在“" + schoolInfo.getName() + "”没有可发放科目，请查看在“" + schoolInfo.getName() + "”是否有带班");
        }

        List<BookStudent> bookGrantInfoRsList = iBookStudentService.getDistributable(yearPart, quarterNum, schoolId, subjectsId, teacherId, status, type, bookTextType, isDetails, studentName, gradeId, bookTextId, classTypeId, yearClassId, lessonNum);

        return new Result(Code.OK, bookGrantInfoRsList, Code.GET_OK_MSG);
    }


    /**
     * 按老师发放
     *
     * @param bookGrantRs
     * @return
     */
    @PostMapping("/saveDistributable")
    public Result saveDistributable(@RequestBody BookGrantRs bookGrantRs) {
        Integer yearPart = bookGrantRs.getYearPart();
        Integer quarterNum = bookGrantRs.getQuarterNum();

        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }

        if (bookGrantRs.getSchoolId() == null) {
            return new Result(Code.ERROR, "", "请选择发放校区");
        }

        if (bookGrantRs.getTeacherId() == null) {
            return new Result(Code.ERROR, "", "没有发放老师，请重新扫脸");
        }

        Long subjectsId = gradeMapper.getSubjectsForTeacherId(yearPart, quarterNum, bookGrantRs.getSchoolId(), bookGrantRs.getTeacherId());
        if (subjectsId == null) {
            return new Result(Code.ERROR, "", "该老师没有可发放科目，查看是否有带班班级");
        }

        if (bookGrantRs.getBookGrantInfoRsList() == null || bookGrantRs.getBookGrantInfoRsList().isEmpty()) {
            return new Result(Code.ERROR, "", "请选择发放数据");
        }

        bookGrantRs.setSubjectsId(subjectsId);

        boolean bookGrant = iBookStudentService.bookGrant(yearPart, quarterNum, bookGrantRs.getOssImageUrl(), this.adminId, bookGrantRs);

        if (!bookGrant) {
            return new Result(Code.ERROR, "", "发放失败");
        }

        return new Result(Code.OK, "", "发放成功");
    }

    /**
     * 学生可发放
     *
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @GetMapping("/getDistributableStudent")
    public Result getDistributableStudent(
            @RequestParam(value = "yearPart", required = false) Integer yearPart,
            @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "studentId", required = false) Long studentId,
            @RequestParam(value = "subjectsId", required = false) Long subjectsId,
            @RequestParam(value = "status", required = false, defaultValue = "4") Integer status
    ) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }

        if (schoolId == null) {
            return new Result(Code.ERROR, "", "请选择校区");
        }

        if (studentId == null) {
            return new Result(Code.ERROR, "", "没有学生，请重新扫脸");
        }

        Integer bookTextType = 1;//1学生用书

        List<BookStudent> bookGrantInfoRsList = iBookStudentService.getDistributableStudent(yearPart, quarterNum, schoolId, subjectsId, studentId, status, bookTextType);

        return new Result(Code.OK, bookGrantInfoRsList, Code.GET_OK_MSG);
    }

    /**
     * 按学生发放
     *
     * @param bookGrantRs
     * @return
     */
    @PostMapping("/saveDistributableStudent")
    public Result saveDistributableStudent(@RequestBody BookGrantRs bookGrantRs) {
        Integer yearPart = bookGrantRs.getYearPart();
        Integer quarterNum = bookGrantRs.getQuarterNum();

        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }
        if (bookGrantRs.getBookGrantInfoRsList() == null || bookGrantRs.getBookGrantInfoRsList().isEmpty()) {
            return new Result(Code.ERROR, "", "请选择发放数据");
        }

        for (BookGrantInfoRs bookGrantInfo : bookGrantRs.getBookGrantInfoRsList()) {
            if (bookGrantInfo.getBookTextId() == null) {
                return new Result(Code.ERROR, "", "课程不能为空，发放失败，请与智能部联系");
            }
            if (bookGrantInfo.getSubjectsId() == null) {
                return new Result(Code.ERROR, "", "科目不能为空，发放失败，请与智能部联系");
            }
            if (bookGrantInfo.getClassTypeId() == null) {
                return new Result(Code.ERROR, "", "班型不能为空，发放失败，请与智能部联系");
            }
            if (bookGrantInfo.getYearClassId() == null) {
                return new Result(Code.ERROR, "", "年级不能为空，发放失败，请与智能部联系");
            }
        }

        boolean rs = iBookStudentService.bookGrantStudent(yearPart, quarterNum, bookGrantRs.getOssImageUrl(), this.adminId, bookGrantRs);
        if (rs) {
            return new Result(Code.OK, "", Code.SAVE_OK_MSG);
        } else {
            return new Result(Code.ERROR, "", "发放失败，请与智能部联系");
        }

    }

}
